﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Sharp.DataTransferObject;

namespace Sharp.Platform.Mvc
{
    public class PermissionScan
    {
        /// <summary>
        /// 自动生成权限数据的类别
        /// </summary>
        public string[] AutoCategory = new[] { "02", "09" };
        /// <summary>
        /// 获取程序集的功能点
        /// </summary>
        /// <returns></returns>
        public IList<PermissionDTO> GetAllActionByAssembly()
        {
            var result = new List<PermissionDTO>();

            var types = Assembly.Load("Sharp.WebBooter").GetTypes();

            foreach (var type in types.Where(x => x.IsSubclassOf(typeof(Controller))))
            {
                var members = type.GetMethods();
                foreach (var member in members)
                {
                    if (member.ReturnType == typeof(ActionResult) || member.ReturnType.IsSubclassOf(typeof(ActionResult)))
                    {
                        var permissionAttribute = member.GetCustomAttributes<PermissionAttribute>(true).FirstOrDefault();
                        if (permissionAttribute == null)
                        {
                            continue;
                        }
                        var areas = "/";
                        if (type.Namespace.Contains(".Areas."))
                        {
                            areas += Regex.Match(type.Namespace, @"Areas\.(.*?)\.Controllers").Groups[1].Value;
                            areas += "/";
                        }

                        var ap = new PermissionDTO
                        {
                            Title = permissionAttribute.Name,
                            OrderIndex = permissionAttribute.Order,
                            Code = "",
                            Route =
                               areas + member.DeclaringType.Name.Substring(0, member.DeclaringType.Name.Length - 10) +
                                "/" + member.Name,// 去掉“Controller”后缀
                            Category = permissionAttribute.Category
                        };
                        if (!permissionAttribute.Parent.IsNullOrEmpty())
                        {
                            ap.Route = permissionAttribute.Parent + "/" + member.Name;
                        }

                        if (result.All(r => r.Route != ap.Route))
                        {
                            result.Add(ap);
                        }
                    }

                }

            }
            return result;
        }
    }
}
